package com.carkeeper.canal.Listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.carkeeper.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 服务目录监听
 */
@CanalEventListener
public class CatalogueListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 监听数据改变的方法
     * @param eventType  数据类型
     * @param rowData  数据库行数据
     * @ListenPoint 表示监听点
     * schema表示监听的数据库，table表示监听的数据库表
     */
    @ListenPoint(schema = "carkeeper_shop",table = "tb_service")
    public void tbUpdate(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        System.out.println("数据库发生改变");
        //修改前数据
        Map oldMap=new HashMap<>();
        for(CanalEntry.Column column: rowData.getBeforeColumnsList()) {
            oldMap.put(column.getName(),column.getValue());
            System.out.println("改变前"+column.getName()+":"+column.getValue());
        }

        //修改后数据
        Map newMap=new HashMap<>();
        for(CanalEntry.Column column: rowData.getAfterColumnsList()) {
            newMap.put(column.getName(),column.getValue());
            System.out.println("改变后"+column.getName()+":"+column.getValue());
        }

        //status  由0改为1表示上架
        if("0".equals(oldMap.get("status")) && "1".equals(newMap.get("status")) ){
            rabbitTemplate.convertAndSend(RabbitMQConfig.SERVICE_UP_EXCHANGE,"",newMap.get("id")); //发送到mq商品上架交换器上
            System.out.println("上传id到mq："+newMap.get("id"));
        }

        //获取最新下架的商品 由1--->0
        if("1".equals(oldMap.get("status")) && "0".equals(newMap.get("status"))){
            //发送到rabbitmq中,把spuId发送出去
            rabbitTemplate.convertAndSend(RabbitMQConfig.SERVICE_DOWN_EXCHANGE,"",newMap.get("id"));
        }
    }
}
